import { useEffect, useRef } from 'react';
import { gsap } from 'gsap';
import styles from './index.module.scss';

interface TextAnimateProps {
  text: string;
  duration?: number;
  delay?: number;
  scrambleDuration?: number;
  className?: string;
  color?: string;
  fontSize?: string;
  hoverColor?: string;
}

export default function TextAnimate({ 
  text, 
  duration = 2, 
  delay = 0, 
  scrambleDuration = 0.6,
  className = '',
  color = '#333',
  fontSize = '24px',
  hoverColor = '#007bff'
}: TextAnimateProps) {
  const textRef = useRef<HTMLDivElement>(null);
  const timelineRef = useRef<gsap.core.Timeline | null>(null);
  // 用ref存储当前字符数组，避免闭包问题
  const charsRef = useRef<string[]>([]);

  const getScrambleChar = () => {
    const chars = '▄▀▄▀▄▀▄▀▄▀';
    return chars[Math.floor(Math.random() * chars.length)];
  };

  // 提取鼠标移入动画逻辑为独立函数（确保每次调用都使用最新状态）
  const handleMouseEnter = (span: HTMLElement, index: number) => {
    console.log(index, span);
    // 停止span上所有正在运行的动画，避免状态冲突
    gsap.killTweensOf(span);
    
    // 强制设置为马赛克状态（立即生效）
    gsap.set(span, {
      textContent: getScrambleChar(),
      opacity: 1,
      scale: 1,
      color: color,
      immediateRender: true // 强制立即渲染，避免被其他动画覆盖
    });

    // 转换为真实文字
    gsap.to(span, {
      duration: 0.4,
      textContent: charsRef.current[index], // 使用ref中的最新字符数组
      opacity: 1,
      scale: 1,
      color: color,
      ease: "back.out(1.7)",
    });
  };

  useEffect(() => {
    if (!textRef.current || !text) return;

    // 清理之前的动画和事件
    if (timelineRef.current) {
      timelineRef.current.kill();
    }
    // 存储当前字符到ref，避免闭包问题
    charsRef.current = text.split('');
    const element = textRef.current;
    const chars = charsRef.current;
    
    // 清空容器，重新创建字符元素
    element.innerHTML = '';
    const scrambleSpans = chars.map((_, index) => {
      const span = document.createElement('span');
      span.style.display = 'inline-block';
      span.style.opacity = '0';
      span.style.transform = 'scale(0)';
      span.style.transition = 'none';
      span.style.cursor = 'pointer';
      span.style.color = color;
      span.style.fontSize = fontSize;
      
      // 只绑定一次事件，使用索引关联ref中的字符
      span.addEventListener('mouseenter', () => {
        handleMouseEnter(span, index);
      });
      
      element.appendChild(span);
      return span;
    });

    // 创建主动画时间轴
    const tl = gsap.timeline({ delay });
    timelineRef.current = tl;

    // 初始马赛克状态
    tl.set(scrambleSpans, {
      textContent: () => getScrambleChar(),
      opacity: 1,
      scale: 1,
      color: color
    });

    // 马赛克闪烁效果
    if (scrambleDuration > 0) {
      const updateInterval = 0.08;
      const totalUpdates = Math.floor(scrambleDuration / updateInterval);
      
      for (let i = 0; i < totalUpdates; i++) {
        const startTime = i * updateInterval;
        tl.to(scrambleSpans, {
          duration: 0.02,
          opacity: 0.3,
          ease: "power2.out"
        }, startTime);
        
        tl.to(scrambleSpans, {
          duration: 0.01,
          textContent: () => getScrambleChar(),
          ease: "none"
        }, startTime + 0.02);
        
        tl.to(scrambleSpans, {
          duration: 0.02,
          opacity: 1,
          ease: "power2.in"
        }, startTime + 0.03);
      }
    }

    // 转换为真实文字
    tl.to(scrambleSpans, {
      duration: 1,
      textContent: (i: number) => chars[i],
      opacity: 1,
      scale: 1,
      color: color,
      ease: "back.out(1.7)",
      stagger: 0.05
    });

    tl.to(scrambleSpans, {
      duration: 0.2,
      scale: 1,
      ease: "power2.in"
    });

    // 清理函数：移除事件监听，避免内存泄漏
    return () => {
      timelineRef.current?.kill();
      scrambleSpans.forEach(span => {
        span.removeEventListener('mouseenter', () => {}); // 移除事件监听
      });
    };
  }, [text, duration, delay, scrambleDuration, color, fontSize, hoverColor]);

  return (
    <div 
      ref={textRef} 
      className={`${styles.textAnimate} ${className}`}
    />
  );
}